<?php

namespace App\Jobs;

use App\Models\ActivityUploads;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use OSS\OssClient;
use OSS\Core\OssException;

class AliOssUploadJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $filepath;
    protected $uid;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($uid,$filepath)
    {
        //
        $this->uid=$uid;
        $this->filepath=$filepath;
        $this->onQueue("ali_oss_uploader");
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        $bucket=env("ALIYUN_BUCKET");
        $object=uniqid().".".explode(".",basename($this->filepath))[1];
        $ossClient = $this->getOssClient();
        $storename="alioss";
        $storedata=$ossClient->uploadFile($bucket, $object, $this->filepath);
        $upload=ActivityUploads::newUpload($this->uid,$storename,$storedata);
        echo $storedata['info']['url'].PHP_EOL;

    }
    public function getOssClient()
    {
        $accessKeyId=env("ALIYUN_ACCESS_KEY_ID");
        $accessKeySecret=env("ALIYUN_ACCESS_KEY_SECRET");
        $endpoint=env("ALIYUN_ENDPOINT");
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint, false);
        } catch (OssException $e) {
            printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
            printf($e->getMessage() . "\n");
            return null;
        }
        return $ossClient;
    }
}
